
<template>
    <div class="field-control">
        <SelectControl :name="code" :optionKey="rangeset.key || 'id'" :disabled="disabled" :renderTpl="renderTpl" :data="initData" :postData="fetchData" :path="fetchPath" :option-key="model.rangeset?model.rangeset.key:'id'" :option-code="model.rangeset?model.rangeset.name:'name'" :initValue="value" @selectChange="selectChange" @input="val($event)">
        </SelectControl>
        <div class="field-message" v-show="!validate">{{message}}</div>
    </div>
</template>
<script>
import $ from "@/common";
$;
import base from "./base";
import SelectControl from "@/components/selector";
export default {
  extends: base,
  data() {
    return {
      mapping: null
    };
  },
  computed: {
    renderTpl() {
      if (this.rangeset) {
        return this.rangeset.tpl_list || this.rangeset.tpl_res;
      } else {
        return null;
      }
    },
    initData() {
      if (this.rowData && this.rowData[this.code] && this.rangeset) {
        return [
          {
            [this.rangeset.key || "id"]: this.rowData[this.code],
            name: this.rowData[this.code + "_name"] || this.rowData[this.code]
          }
        ];
      }
    },
    fetchPath() {
      if (this.rangeset) {
        if (this.rangeset.path) {
          return this.rangeset.path;
        } else if (this.rangeset.dataset || this.rangeset.code) {
          return `/service/{app}/dataset/data/${this.rangeset.dataset ||
            this.rangeset.code}`;
        }
      }
    },
    fetchData() {
      var data = {};
      var param = {
        ...this.rowData
      };
      param.parent = this.parentData || {};
      for (let i in this.fetchDataset) {
        data[i] = $.composeValue(this.fetchDataset[i], param);
      }
      return data;
    },
    fetchDataset() {
      if (this.mapping) {
        return $.parseStringEq(this.mapping);
      } else {
        return {};
      }
    },
    rangeset() {
      var rangeset = this.fieldModel.rangeset || {};
      if (rangeset && typeof rangeset === "string") {
        try {
          rangeset = JSON.parse(rangeset);
        } catch (ex) {
          rangeset = {
            code: rangeset
          };
        }
      }
      return rangeset || {};
    }
  },
  methods: {
    selectChange(v) {
      this.$emit("extInput", {
        code: this.code + "_name",
        value: v && v.name
      });
      if (this.rangeset.mapping) {
        for (let i in this.rangeset.mapping) {
          this.$emit("extInput", {
            code: i,
            value: v && v[this.rangeset.mapping[i]]
          });
        }
      }
    }
  },
  created() {
    if (
      this.fieldModel &&
      this.fieldModel.param &&
      this.fieldModel.param.mapping
    ) {
      this.mapping = this.fieldModel.param.mapping;
    }
  },
  components: {
    SelectControl
  }
};
</script>
<style lang="less">

</style>
